package com.example.helloworld

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.util.Locale

class Activity4 : AppCompatActivity() {
    private var elapsedTime: Long = 0
    private var isRunning = false
    private lateinit var handler: Handler
    private lateinit var tvTime: TextView

    private val timerRunnable = object : Runnable {
        override fun run() {
            if (isRunning) {
                elapsedTime += 10
                updateTimeUI()
                handler.postDelayed(this, 10)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity4)
        title = "Activity4（计时器）"

        tvTime = findViewById(R.id.tv_time)
        val btnStart = findViewById<Button>(R.id.btn_start)
        val btnPause = findViewById<Button>(R.id.btn_pause)
        val btnReset = findViewById<Button>(R.id.btn_reset)

        handler = Handler(Looper.getMainLooper())

        if (savedInstanceState != null) {
            elapsedTime = savedInstanceState.getLong("elapsedTime", 0L)
            isRunning = savedInstanceState.getBoolean("isRunning", false)
            updateTimeUI()
            if (isRunning) {
                startTimer()
            }
        } else {
            tvTime.text = getString(R.string.timer_default)
        }

        btnStart.setOnClickListener {
            if (!isRunning) {
                isRunning = true
                startTimer()
            }
        }

        btnPause.setOnClickListener {
            isRunning = false
            handler.removeCallbacks(timerRunnable)
        }

        btnReset.setOnClickListener {
            isRunning = false
            handler.removeCallbacks(timerRunnable)
            elapsedTime = 0
            updateTimeUI()
        }
    }

    private fun startTimer() {
        handler.post(timerRunnable)
    }

    private fun updateTimeUI() {
        val minutes = (elapsedTime / 60000) % 60
        val seconds = (elapsedTime / 1000) % 60
        val milliseconds = elapsedTime % 1000
        val timeText = String.format(Locale.getDefault(), "%02d:%02d.%03d", minutes, seconds, milliseconds)
        tvTime.text = timeText
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putLong("elapsedTime", elapsedTime)
        outState.putBoolean("isRunning", isRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(timerRunnable)
    }
}